const Service = require('egg').Service;

class MonitorService extends Service{
	async index (){
		return {
			status: 0,
			data: 33322,
			msg: ''
		}
	}

	getModel (type, ctx) {
		let Table ;
		switch(type){
			case 'ajax' : Table = ctx.model.Ajax; break;
			case 'error' : Table = ctx.model.Error; break;
			case 'page' : Table = ctx.model.Page; break;
			case 'device' : Table = ctx.model.Device; break;
			default:  Table = ctx.model.Error;
		}
		return Table;
	}
	/**
	 * 页面/请求数据统计
	 * @param {*} type 
	 * @param {*} params 
	 * @returns 
	 */
	async statistics(type,params){
		const {ctx} = this;
		let Table  = this.getModel(type,ctx)
		const list = await Table.aggregate(params)
		return {list};
	}

	async getList(params,pageInfo){
		const {ctx} = this;
		let startTime = Date.now();
		// 批量添加错误日志
		let {pageNum = 1,pageSize = 10} = pageInfo;
		// 查询对应的数据库地址
		const reportType = params.report_type;
		let Table  = this.getModel(reportType,ctx)
		delete params.report_type;
		// 模糊查询处理
		Object.keys(params).forEach(key => {
			params[key] = new RegExp(params[key])
		})
		// 查询总数
		const total = await Table.find(params).count();
		// 查询列表
		let list = [];
		if(total !== 0){
			if(total/pageSize < pageNum){
				pageNum = Math.ceil(total/pageSize)
			}
			list = await Table.find(params).skip(pageSize* (pageNum-1)).limit(parseInt(pageSize)).sort({create_time: -1})
		}
		let duration = Date.now() - startTime;
		console.log("【查询耗时】：",parseInt(duration))
		return {
			pageNum,
			pageSize,
			total,
			list 
		}
	}

}

module.exports = MonitorService;